package cn.ike.web.controller.cargo;

import cn.ike.domain.cargo.ContractProduct;
import cn.ike.domain.cargo.ContractProductExample;
import cn.ike.domain.cargo.Factory;
import cn.ike.domain.cargo.FactoryExample;
import cn.ike.service.cargo.ContractProductService;
import cn.ike.service.cargo.FactoryService;
import cn.ike.web.controller.BaseController;
import cn.ike.web.utils.FileUploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import lombok.extern.log4j.Log4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@Log4j
@RequestMapping("/cargo/contractProduct")
public class ContractProductController extends BaseController {

    @Reference
    private ContractProductService contractProductService;
    @Reference
    private FactoryService factoryService;
    // 文件上传
    @Autowired
    private FileUploadUtil fileUploadUtil;

    /**
     * 1.货物列表分页
     */
    @RequestMapping("/list")
    public ModelAndView list(String contractId,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "5") Integer pageSize) {
        ModelAndView model = new ModelAndView();
        try {
            log.info("执行货物列表分页开始...");
            // 创建货物查询条件
            ContractProductExample productExample = new ContractProductExample();
            productExample.createCriteria().andContractIdEqualTo(contractId);
            // 查询货物
            PageInfo<ContractProduct> pageInfo = contractProductService.findByPage(productExample, pageNum, pageSize);

            // 创建货物工厂查询条件
            FactoryExample factoryExample = new FactoryExample();
            factoryExample.createCriteria().andCtypeEqualTo("货物");
            // 查询货物工厂
            List<Factory> factoryList = factoryService.findAll(factoryExample);

            model.addObject("pageInfo", pageInfo);
            model.addObject("factoryList", factoryList);
            model.addObject("contractId", contractId);
            model.setViewName("cargo/product/product-list");
            log.info("执行货物列表分页结束...");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行货物列表分页出现异常！", e);
        }
        return model;
    }

    /**
     * 2.货物的添加或修改
     * 文件上传参数： <input type="file"  name="productPhoto" >
     */
    @RequestMapping("/edit")
    public ModelAndView edit(ContractProduct contractProduct, MultipartFile productPhoto) {
        ModelAndView model = new ModelAndView();
        String contractId = contractProduct.getContractId();
        try {
            String productId = contractProduct.getId();
            if (StringUtils.isEmpty(productId)) {
                log.info("执行货物的添加或修改开始...");
                contractProduct.setCompanyId(getLoginCompanyId());
                contractProduct.setCompanyName(getLoginCompanyName());
                /*处理文件上传*/
                if (productPhoto != null){
                    // 处理文件上传
                    String fileUrl = "http://" + fileUploadUtil.upload(productPhoto);
                    contractProduct.setProductImage(fileUrl);
                }
                /*记录创建人、创建人的部门(后期列表数据权限控制使用)*/
                contractProduct.setCreateBy(getLoginUser().getId());
                contractProduct.setCreateDept(getLoginUser().getDeptId());
                contractProductService.save(contractProduct);
                log.info("执行货物的添加或修改结束...");
            } else {
                log.info("执行货物的添加或修改开始...");
                contractProductService.update(contractProduct);
                log.info("执行货物的添加或修改结束...");
            }
            model.setViewName("redirect:/cargo/contractProduct/list?contractId=" + contractId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行货物的添加或修改出现异常！", e);
        }
        return model;
    }

    /**
     * 3.进入货物的修改页面
     */
    @RequestMapping("/toUpdate")
    public ModelAndView toUpdate(String id) {
        ModelAndView model = new ModelAndView();
        try {
            log.info("执行货物的修改开始...");
            //1. 根据货物id查询
            ContractProduct contractProduct = contractProductService.findById(id);
            // 查询生产厂家
            FactoryExample factoryExample = new FactoryExample();
            factoryExample.createCriteria().andCtypeEqualTo("货物");
            List<Factory> factoryList = factoryService.findAll(factoryExample);

            model.addObject("contractProduct", contractProduct);
            model.addObject("factoryList", factoryList);
            model.setViewName("cargo/product/product-update");
            log.info("执行货物的修改结束...");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行货物的修改出现异常！", e);
        }
        return model;
    }

    /**
     * 删除货物
     */
    @RequestMapping("/delete")
    public ModelAndView delete(String id, String contractId) {
        ModelAndView model = new ModelAndView();
        try {
            log.info("执行删除货物开始...");
            contractProductService.delete(id);
            model.setViewName("redirect:/cargo/contractProduct/list?contractId=" + contractId);
            log.info("执行删除货物结束...");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行删除货物出现异常！", e);
        }
        return model;
    }

    /**
     *  进入货物上传列表
     */
    @RequestMapping("/toImport")
    public ModelAndView toImport(String contractId) {
        ModelAndView model = new ModelAndView();
        model.addObject("contractId", contractId);
        model.setViewName("cargo/product/product-import");
        return model;
    }

    /**
     *  货物上传
     *  参数：
     *      contractId 购销合同id，给某个购销合同添加货物
     *      file       上传的文件
     */
    @RequestMapping("/import")
    public ModelAndView importExcel(String contractId, MultipartFile file) {
        ModelAndView model = new ModelAndView();
        try {
            log.info("执行货物上传开始...");
            /*ApachePOI解析上传的Excel数据，实现添加货物*/
            Workbook workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);

            // 获取总行数
            int rowCount = sheet.getPhysicalNumberOfRows();

            // 遍历: 从第二行开始遍历
            Row row = null;
            for (int i = 1; i < rowCount; i++) {
                // 先获取第二行数据
                row = sheet.getRow(1);

                // 创建货物对象并封装
                ContractProduct cp = new ContractProduct();
                cp.setFactoryName(row.getCell(1).getStringCellValue());
                cp.setProductNo(row.getCell(2).getStringCellValue());
                // 注意：如果excel中内容数据是数值类型，获取数值要用getNumericCellValue()
                cp.setCnumber((int) row.getCell(3).getNumericCellValue());
                cp.setPackingUnit(row.getCell(4).getStringCellValue());
                //cp.setLoadingRate(String.valueOf(row.getCell(5).getNumericCellValue()));
                cp.setLoadingRate(String.valueOf(row.getCell(5).getRichStringCellValue()));
                cp.setBoxNum((int) row.getCell(6).getNumericCellValue());
                cp.setPrice(row.getCell(7).getNumericCellValue());
                cp.setProductDesc(row.getCell(8).getStringCellValue());
                cp.setProductRequest(row.getCell(9).getStringCellValue());
                // 注意： 必须要设置购销合同ID  【不要忘记， 查看表...】
                cp.setContractId(contractId);
                // 设置厂家id
                FactoryExample factoryExample = new FactoryExample();
                factoryExample.createCriteria().andFactoryNameEqualTo(cp.getFactoryName());
                List<Factory> factoryList = factoryService.findAll(factoryExample);
                Factory factory = null;
                if (factoryList != null && factoryList.size() > 0){
                    factory = factoryList.get(0);
                }
                if (factory != null){
                    cp.setFactoryId(factory.getId());
                }
                // 设置企业信息
                cp.setCompanyId(getLoginCompanyId());
                cp.setCompanyName(getLoginCompanyName());

                // 添加货物
                contractProductService.save(cp);
            }
            // 购销合同添加货物完成后，跳转到购销合同列表
            model.setViewName("redirect:/cargo/contract/list");
            log.info("执行货物上传结束...");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行货物上传出现异常！", e);
        }
        return model;
    }

}
